<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\OrderCreatePost;
use App\library\services\OrderService;
use App\library\services\UserReleaseService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    /**
     * Author:Zhongyuan Lu
     * 订单创建
     * @param OrderCreatePost $request
     * @return mixed
     */
    public function create(OrderCreatePost $request)
    {
        $uid = Request()->uid;
        $params = $request->validated();

        DB::beginTransaction();
        try {
            //发布信息入库
            $userRelease = UserReleaseService::createRelease($params);
            if ($userRelease['code'] !== 200) {
                return $this->fail($userRelease['message']);
            }

            //发布图片入库
            $releaseImage = UserReleaseService::createReleaseImage($userRelease['data'],$params);
            if ($releaseImage['code'] !== 200) {
                return $this->fail($releaseImage['message']);
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->fail($exception->getMessage());
        }

        //订单创建
        $order = OrderService::createOrder($uid,$userRelease['data'],$params['type']);
        if ($order['code'] !== 200) {
            return $this->fail($order['message'],[],1001);
        }

        //生产者
        OrderService::queOrder($order['data']);
        return $this->success('发布成功', $order['data']);
    }
}
